package dept

import (
	"context"
	"devops-super/api/dept/v1"
	"devops-super/internal/dao"
	"devops-super/internal/model/do"
	"devops-super/internal/model/entity"
	"devops-super/internal/service"
	"errors"
)

func (c *ControllerV1) Del(ctx context.Context, req *v1.DelReq) (res *v1.DelRes, err error) {
	old := &entity.Dept{}
	err = dao.Dept.Ctx(ctx).Where("id", req.Id).Scan(old)
	if err != nil {
		return
	}
	if old.ParentId == 0 {
		err = errors.New("top dept cannot be deleted")
		return
	}
	count, err := dao.User.Ctx(ctx).Where(dao.User.Columns().DeptId, req.Id).Count()
	if err != nil || count > 0 {
		err = errors.New("delete users belong this dept first")
		return
	}

	err = service.Role().Del(ctx, &do.Role{Id: req.Id})
	if err != nil {
		return nil, err
	}
	where := &do.Dept{
		Id: req.Id,
	}
	err = service.Dept().Del(ctx, where)
	if err != nil {
		return nil, err
	}
	return
}
